import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {Icon, View, Text, Checkbox, Navigator, Block, Button, Image, Picker} from '@tarojs/components';
import {AtForm, AtIcon, AtInput} from 'taro-ui';
import {user} from '../../utils/user.service';
import {http} from '../../utils/http';
import {
  LIAN_CREATE_ORDER,
  LIAN_PAY,
  LIAN_GET_PAY_TOKEN, ADDRESS_DEFAULT,
  PC_LIANLIAN_QRCODE, PC_ORDER_STATUS, TARO_ENV
} from '../../constants/api';
import {DateType} from '../../reducers/select-date';
import {getTempSellerId, vcmonitor} from '../../utils/tools'
import NumberInput from "../components/number-input/number-input";
import {h5Wx} from "../../utils/h5.service";
import {platform} from "../../utils/platform-settting.service";
import {Address} from "../../utils/server.interface";
import {newHttp} from "../../utils/request";
import GzhAuth from "../../components/gzh-auth/gzh-auth";
import './pay.scss';

interface StateType {
  num: number
  totalFee: number
  isiPhonex: boolean
  platformSet: any
  addobj: any
  detail: any
  submiting: boolean
  isOpened: boolean
  contactData: any
  tempSellerId: any
  pcQrcodeShow: boolean
  pcqrcode: string
  env: string
  paySuccessShow: boolean
}

type PageStateProps = {
  selectDate: DateType
}

type PageDispatchProps = {}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Confirm {
  props: IProps
}

class Confirm extends Component {
  state: StateType = {
    addobj: {},
    contactData: {
      identity_num: '',
      travel_date: '',
      remark: '',
      linkman: '',
      phone: '',
      address: ''
    },
    isiPhonex: false,
    platformSet: {},
    submiting: false,
    num: 1,
    detail: {},
    totalFee: 0,
    isOpened: false,
    pcQrcodeShow: false,
    pcqrcode: '',
    tempSellerId: '',
    env: '',
    paySuccessShow: false
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const login = await user.checkLogin()
    if (!login) {
      user.jumpLogin()
      return false
    }
    const {itemId, productId, locationId} = Taro.getCurrentInstance().router.params
    if (!itemId || !productId || !locationId) {
      Taro.showToast({
        title: '参数错误',
        icon: 'none'
      })
      Taro.navigateBack()
      return false
    }
    let tempSellerId = getTempSellerId(this)
    this.setState({tempSellerId})
    const platformSet = await platform.getSetting()
    if (platformSet.platformName) {
      Taro.setNavigationBarTitle({
        title: platformSet.platformName
      })
    }
    const data = await http.postCar(LIAN_CREATE_ORDER, {tempSellerId,itemId, productId, locationId})
    if (!data) {
      return false
    }
    this.orderNum = data.orderNum
    const res = await http.postCar(LIAN_GET_PAY_TOKEN, {tempSellerId,orderNum: data.orderNum, amount: 1})
    this.payToken = res.payToken
    this.setState({platformSet, detail: data, num: res.amount, totalFee: res.total_fee})
  }

  orderNum = ''
  payToken = ''

  async componentDidShow() {
    vcmonitor(this)
    const {contactData} = this.state
    const addobj = await http.carGet<Address>(ADDRESS_DEFAULT)
    if (addobj) {
      const add = addobj.add ? addobj.add.replace(/,/g, "") : ''
      const address = addobj.address
      contactData['address'] = add + address
    }
    this.setState({addobj, contactData, env: Taro.getCurrentInstance().router.params.env})
  }

  submitCheck() {
    const {contactData, detail, addobj} = this.state
    if (Number(detail.isRequireBuyerAddress)) {
      if (!addobj || !addobj.name || !addobj.phone){
        Taro.showToast({title: '请填写地址信息', icon: 'none'})
        return false
      }
      contactData.linkman = addobj.name
      contactData.phone = addobj.phone
    }
    if (!contactData.linkman) {
      Taro.showToast({title: '请填写姓名', icon: 'none'})
      return false
    }
    if (!contactData.phone) {
      Taro.showToast({title: '请填写手机号码', icon: 'none'})
      return false
    }
    if (Number(detail.isRequireBuyerIdcard) && !contactData.identity_num) {
      Taro.showToast({title: '请填写身份证号', icon: 'none'})
      return false
    }
    if (Number(detail.orderShowDate) && !contactData.travel_date) {
      Taro.showToast({title: '请填写使用日期', icon: 'none'})
      return false
    }
    if (Number(detail.isRequireBuyerAddress) && !contactData.address) {
      Taro.showToast({title: '请填写配送地址', icon: 'none'})
      return false
    }
    const r = /^1[0-9]{10}$/;　　//1开头0-9内十位数
    if (!r.test(contactData.phone)) {
      Taro.showToast({title: '手机号码格式不正确', icon: 'none'})
      return false
    }
    this.setState({submiting: true}, async () => {
      const {contactData, totalFee, tempSellerId} = this.state
      const {linkman, phone, identity_num, travel_date, remark, address} = contactData
      const confirmRet = await http.postCar(LIAN_PAY, {
        tempSellerId,
        payToken: this.payToken,
        orderNum: this.orderNum,
        linkman,
        phone,
        identity_num,
        travel_date,
        remark,
        address: Number(detail.isRequireBuyerAddress) ? address : '',
        paySource: TARO_ENV === 'h5' ? 'gongzhonghao' : '',
        rout: this.state.env == 'pc' ? 'pc' : ''
      })
      if (confirmRet) {
        this.setState({submiting: false})
        Taro.showLoading({title: '支付中...'})
        if (process.env.TARO_ENV == 'weapp') {
          Taro.requestPayment({
            timeStamp: confirmRet.timeStamp || '',
            nonceStr: confirmRet.nonceStr || '',
            package: confirmRet.package || '',
            signType: confirmRet.signType || 'MD5',
            paySign: confirmRet.paySign || '',
            success: function (data) {
              Taro.redirectTo({url: '/main/order/success?pay=' + totalFee})
            },
            fail: function (data) {
              Taro.showModal({
                title: '提示',
                content: '超时未支付系统将自动取消订单，现在去付款？',
                success: function (res) {
                  if (res.confirm) {
                    Taro.redirectTo({
                      url: '/main/order/order?status=0'
                    })
                  }
                }
              });
            },
            complete: function () {
              Taro.hideLoading()
            }
          })
        } else {
          if (this.state.env == 'pc') {
            const data = {
              appId: confirmRet.appId || '',
              timeStamp: confirmRet.timeStamp || '',
              nonceStr: confirmRet.nonceStr || '',
              package: confirmRet.package || '',
              signType: confirmRet.signType || 'MD5',
              paySign: confirmRet.paySign || ''
            }
            if (process.env.TARO_ENV === 'h5') {
              data['paySource'] = 'gongzhonghao'
            }
            const pcQrode = await newHttp.catchGet(PC_LIANLIAN_QRCODE + this.orderNum, data)
            this.setState({pcqrcode: pcQrode, pcQrcodeShow: true})
            const time = setInterval(async () => {
              const status = await newHttp.catchGet(PC_ORDER_STATUS + this.orderNum)
              if (status.isPay) {
                clearInterval(time)
                this.setState({paySuccessShow: true})
              }
            }, 1000)
          } else {
            h5Wx.chooseWXPay({
              appId: confirmRet.appId || '',
              timeStamp: confirmRet.timeStamp || '',
              nonceStr: confirmRet.nonceStr || '',
              package: confirmRet.package || '',
              signType: confirmRet.signType || 'MD5',
              paySign: confirmRet.paySign || '',
            }, res => {
              Taro.redirectTo({url: '/main/order/success?pay=' + totalFee})
            }, err => {
              Taro.showModal({
                title: '提示',
                content: '超时未支付系统将自动取消订单，现在去付款？',
                success: function (res) {
                  if (res.confirm) {
                    Taro.redirectTo({
                      url: '/main/order/order?status=0'
                    })
                  }
                }
              });
            })
          }

        }
        Taro.hideLoading()
      } else {
        this.setState({submiting: false})
      }
    })
  }

  handleChange(name, value) {
    if (name === 'travel_date') {
      value = value.detail.value
    }
    const {contactData} = this.state
    contactData[name] = value.replace(/\s+/g, '')
    this.setState({contactData})
  }

  async inputNumber(num) {
    if (num === 0 || !this.orderNum) {
      return
    }
    Taro.showLoading({title: '计算中...', mask: true})
    const res = await http.postCar(LIAN_GET_PAY_TOKEN, {tempSellerId: this.state.tempSellerId, orderNum: this.orderNum, amount: num})
    this.payToken = res.payToken
    this.setState({num: res.amount, totalFee: res.total_fee}, async () => {
      Taro.hideLoading()
    })
  }

  render() {
    const dataColor = Taro.getStorageSync('colorData');
    const {paySuccessShow, pcQrcodeShow, pcqrcode, isOpened, contactData, isiPhonex, num, platformSet, submiting, detail, totalFee, addobj} = this.state
    const _env = Taro.getCurrentInstance().router.params.env;
    return (
      <View className='root confirm-root ll-confirm-root'>
        <GzhAuth />
        {detail && !!Number(detail.isRequireBuyerAddress) &&
        <Navigator url={`/other/address/index?id=${addobj ? addobj.id : 0}`} hoverClass='none' className='adddemo'>
          <View className='add-box'>
            {addobj && <View className='add-cont'>
              <View className='name'>{addobj.add ? addobj.add.replace(/,/g, "") : ''}{addobj.address}</View>
              <View className='address'>{addobj.name} <Text>{addobj.phone}</Text></View>
            </View>}
            {!addobj && <View className='addnull'>暂无可用地址,请前往添加</View>}
            <View className='add-icon-right'>
              <AtIcon value='chevron-right' size='16' color='#666' />
            </View>
          </View>
        </Navigator>}
        <View className='good-info'>
          <View className='good-info-header'>
            <View className='header-left'><Image
              src={detail.goodsImg}
              mode='widthFix'
            /></View>
            <View className='header-right'>{detail.goodsName}</View>
          </View>
          <View className='header-footer-info'>{detail.description}</View>
          <View className='input-number'>
            <View className='buy_num'>购买数量</View>
            <NumberInput val={num} step={1} min={1} thisChange={this.inputNumber.bind(this)} />
          </View>
        </View>
        <View className='person'>
          <View className='idcard_box'>
            <View className='user-info'>使用人信息</View>
            {
              detail && <AtForm>
                {!Number(detail.isRequireBuyerAddress) &&
                <AtInput clear name='linkman' type='text'
                  value={contactData.linkman} title='姓名' maxLength={15} placeholder='请输入姓名'
                  onChange={this.handleChange.bind(this, 'linkman')}
                >
                </AtInput>
                }
                {!Number(detail.isRequireBuyerAddress) &&
                <AtInput clear name='phone' type='text'
                  value={contactData.phone} title='手机号码' maxLength={11} placeholder='请输入手机号码'
                  onChange={this.handleChange.bind(this, 'phone')}
                >
                </AtInput>
                }
                {!!Number(detail.isRequireBuyerIdcard) &&
                <AtInput clear name='identity_num' type='text'
                  value={contactData.identity_num} title='身份证号' maxLength={18} placeholder='请输入身份证号'
                  onChange={this.handleChange.bind(this, 'identity_num')}
                >
                </AtInput>
                }
                {!!Number(detail.orderShowDate) &&
                <Picker mode='date' onChange={this.handleChange.bind(this, 'travel_date')}>
                  <AtInput name='travel_date' type='text' editable={false}
                    onClick={() => this.setState({isOpened: true})}
                    value={contactData.travel_date} title='使用日期' placeholder='请输入使用日期'
                  >
                  </AtInput>
                </Picker>
                }
                <AtInput clear name='remark' type='text'
                  value={contactData.remark} title='备注' placeholder='请输入备注（非必填）'
                  onChange={this.handleChange.bind(this, 'remark')}
                >
                </AtInput>
              </AtForm>
            }
          </View>
        </View>
        <View className='agreement'>
          <Checkbox value='true' checked /><Text>我已经查看并同意"产品抢购须知"{platformSet.platform_terms_of_service && '和'}</Text>{platformSet.platform_terms_of_service && <Navigator
            url={`/other/agreement/service?env=${_env}`} className='clause'
          >"{platformSet.platform_terms_of_service}"</Navigator>}
        </View>
        <View style='height: 100px;' />
        <View className={`footer-btn ${isiPhonex ? 'is-iphone-x' : ''}`}>
          <View className='info' />
          <View className='right'>
            <View className='price'>
              <View className='price_text'>合计：</View>
              <View className='price_text'>
                <View className='text font-family-price' style={`color:${dataColor.priceColor}`}>¥ {totalFee}</View>
              </View>
            </View>
            <Block>
              <Button disabled={submiting} loading={submiting} className='btn'
                onClick={this.submitCheck.bind(this)} style={`background-color: ${process.env.mainColor}`}
              >立即支付</Button>
            </Block>
          </View>
        </View>
        {pcQrcodeShow && <View className='curtainRoot'>
          <View className='pc-root'>
            <Image className='pcqrcode' src={pcqrcode} mode='widthFix' />
            <View className='pc-tips'>请扫码进行支付</View>
            <View onClick={() => {
              this.setState({pcQrcodeShow: false, submiting: false})
            }} className='gzh-close'
            >
              <AtIcon value='close' color='#000' />
            </View>
          </View>
        </View>}
        {paySuccessShow && <View className='curtainRoot'>
          <View className='pc-root'>
            <Icon size='60' type='success' />
            <View style='color: #333; font-size: 18px; margin-top: 20px;'>支付成功</View>
          </View>
        </View>}
      </View>
    );
  }
}

export default Confirm as ComponentClass<PageOwnProps, PageState>
